var _ = require("lodash");
var initialState = {
  lists: {},
  carts: [],
  total: 0,
  todetail:false
};

function product(state = initialState, action) {
  switch (action.type) {
    case "GETLISTS":
      return Object.assign({}, state, { lists: action.data });
    //这里action.data而不是state.data是因为：这个data是type为"GETLISTS"下面传过来的data，而increase和decrease只有type，没有data的传递。所以是state.data
    case "ADDTOCART": //添加产品与增加数量（+1）
      var posAdd = _.findIndex(state.carts, { _id: action.data._id });
      if (posAdd === -1) {
        action.data.quantity = 1;
        return {
          ...state,
          carts: [...state.carts, action.data]
        };
      } else {
        state.carts[posAdd].quantity = state.carts[posAdd].quantity + 1;
        return {
          ...state,
          carts: [...state.carts]
        };
      }
    case "REDUCENUM": //减少数量1
      var posRed = _.findIndex(state.carts, { _id: action.data._id });
      if (state.carts[posRed].quantity > 1) {
        state.carts[posRed].quantity = state.carts[posRed].quantity - 1;
      } else {
        console.info("当前数量1，如不需要，请点击删除按钮");
      }
      return {
        ...state,
        carts: [...state.carts]
      };
    case "DELETENUM": //删除
      _.pull(state.carts, action.data);
      return {
        ...state,
        carts: [...state.carts, action.data]
      };
    case "GOTOPRODETAIL":
      return Object.assign({}, state, { todetail: true });
    default:
      return state;
  }
}

export default product;
